<template>
  <div class="user-management">
    <div class="page-header">
      <div class="header-left">
        <h1>用户管理</h1>
        <p class="page-description">管理系统用户、角色权限和组织架构</p>
      </div>
      <div class="header-right">
        <el-button @click="exportUsers">
          <el-icon><Download /></el-icon>
          导出用户
        </el-button>
        <el-button type="primary" @click="showAddUserDialog">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon total">
          <el-icon><UserIcon /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.totalUsers }}</div>
          <div class="stat-label">总用户数</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon active">
          <el-icon><UserFilled /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.activeUsers }}</div>
          <div class="stat-label">活跃用户</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon admin">
          <el-icon><Avatar /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.adminUsers }}</div>
          <div class="stat-label">管理员</div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon new">
          <el-icon><Plus /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.newUsers }}</div>
          <div class="stat-label">本月新增</div>
        </div>
      </div>
    </div>
    
    <!-- 搜索和筛选 -->
    <div class="search-filters">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名、邮箱或真实姓名"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      
      <div class="filter-section">
        <el-select v-model="filters.role" placeholder="角色" clearable @change="handleFilter">
          <el-option label="全部角色" value="" />
          <el-option label="管理员" value="admin" />
          <el-option label="项目经理" value="manager" />
          <el-option label="开发者" value="developer" />
          <el-option label="测试员" value="tester" />
          <el-option label="普通用户" value="user" />
        </el-select>
        
        <el-select v-model="filters.status" placeholder="状态" clearable @change="handleFilter">
          <el-option label="全部状态" value="" />
          <el-option label="活跃" value="active" />
          <el-option label="禁用" value="disabled" />
          <el-option label="待激活" value="pending" />
        </el-select>
        
        <el-select v-model="filters.department" placeholder="部门" clearable @change="handleFilter">
          <el-option label="全部部门" value="" />
          <el-option label="技术部" value="tech" />
          <el-option label="产品部" value="product" />
          <el-option label="设计部" value="design" />
          <el-option label="运营部" value="operation" />
          <el-option label="人事部" value="hr" />
        </el-select>
        
        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="注册开始日期"
          end-placeholder="注册结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleFilter"
        />
        
        <el-button @click="resetFilters">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
      </div>
    </div>
    
    <!-- 用户表格 -->
    <div class="user-table">
      <el-table
        :data="filteredUsers"
        v-loading="loading"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="row.avatar">
                {{ row.username.charAt(0).toUpperCase() }}
              </el-avatar>
              <div class="user-details">
                <div class="username">{{ row.username }}</div>
                <div class="email">{{ row.email }}</div>
                <div class="real-name" v-if="row.realName">{{ row.realName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="角色" width="120">
          <template #default="{ row }">
            <el-tag
              :type="getRoleType(row.role)"
              size="small"
            >
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="部门" width="100">
          <template #default="{ row }">
            <span>{{ getDepartmentText(row.department) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="最后登录" width="150">
          <template #default="{ row }">
            <div v-if="row.lastLoginAt">
              <div>{{ formatDate(row.lastLoginAt) }}</div>
              <div class="last-login-time">{{ formatTime(row.lastLoginAt) }}</div>
            </div>
            <span v-else class="never-login">从未登录</span>
          </template>
        </el-table-column>
        
        <el-table-column label="注册时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button text @click="viewUser(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button text @click="editUser(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-dropdown @command="(command: string) => handleUserAction(command, row)">
              <el-button text>
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="resetPassword">
                    <el-icon><Key /></el-icon>
                    重置密码
                  </el-dropdown-item>
                  <el-dropdown-item command="changeRole">
                    <el-icon><UserFilled /></el-icon>
                    修改角色
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="row.status === 'active' ? 'disable' : 'enable'"
                  >
                    <el-icon><Switch /></el-icon>
                    {{ row.status === 'active' ? '禁用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <el-icon><Delete /></el-icon>
                    删除用户
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedUsers.length > 0">
        <div class="selected-info">
          已选择 {{ selectedUsers.length }} 个用户
        </div>
        <div class="batch-buttons">
          <el-button @click="batchChangeRole">
            <el-icon><UserFilled /></el-icon>
            批量修改角色
          </el-button>
          <el-button @click="batchChangeStatus">
            <el-icon><Switch /></el-icon>
            批量修改状态
          </el-button>
          <el-button type="danger" @click="batchDelete">
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="userDialog.visible"
      :title="userDialog.isEdit ? '编辑用户' : '添加用户'"
      width="600px"
      @close="resetUserForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userFormRules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="userForm.role" placeholder="请选择角色">
                <el-option label="管理员" value="admin" />
                <el-option label="项目经理" value="manager" />
                <el-option label="开发者" value="developer" />
                <el-option label="测试员" value="tester" />
                <el-option label="普通用户" value="user" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-select v-model="userForm.department" placeholder="请选择部门">
                <el-option label="技术部" value="tech" />
                <el-option label="产品部" value="product" />
                <el-option label="设计部" value="design" />
                <el-option label="运营部" value="operation" />
                <el-option label="人事部" value="hr" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="userForm.status" placeholder="请选择状态">
                <el-option label="活跃" value="active" />
                <el-option label="禁用" value="disabled" />
                <el-option label="待激活" value="pending" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!userDialog.isEdit">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="userForm.password"
                type="password"
                placeholder="请输入密码"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注">
          <el-input
            v-model="userForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="userDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveUser" :loading="userDialog.loading">
          {{ userDialog.isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="userDetailDialog.visible"
      title="用户详情"
      width="800px"
    >
      <div class="user-detail" v-if="selectedUser">
        <div class="detail-header">
          <el-avatar :size="80" :src="selectedUser.avatar">
            {{ selectedUser.username.charAt(0).toUpperCase() }}
          </el-avatar>
          <div class="user-basic-info">
            <h3>{{ selectedUser.realName || selectedUser.username }}</h3>
            <p>{{ selectedUser.email }}</p>
            <div class="user-tags">
              <el-tag :type="getRoleType(selectedUser.role)" size="small">
                {{ getRoleText(selectedUser.role) }}
              </el-tag>
              <el-tag :type="getStatusType(selectedUser.status)" size="small">
                {{ getStatusText(selectedUser.status) }}
              </el-tag>
            </div>
          </div>
        </div>
        
        <el-divider />
        
        <div class="detail-content">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-section">
                <h4>基本信息</h4>
                <div class="detail-item">
                  <span class="label">用户名：</span>
                  <span class="value">{{ selectedUser.username }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">真实姓名：</span>
                  <span class="value">{{ selectedUser.realName || '未设置' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">邮箱：</span>
                  <span class="value">{{ selectedUser.email }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">手机号：</span>
                  <span class="value">{{ selectedUser.phone || '未设置' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">部门：</span>
                  <span class="value">{{ getDepartmentText(selectedUser?.department || '') }}</span>
                </div>
              </div>
            </el-col>
            
            <el-col :span="12">
              <div class="detail-section">
                <h4>账户信息</h4>
                <div class="detail-item">
                  <span class="label">注册时间：</span>
                  <span class="value">{{ formatDateTime(selectedUser.createdAt) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">最后登录：</span>
                  <span class="value">
                    {{ selectedUser.lastLoginAt ? formatDateTime(selectedUser.lastLoginAt) : '从未登录' }}
                  </span>
                </div>
                <div class="detail-item">
                  <span class="label">登录次数：</span>
                  <span class="value">{{ selectedUser.loginCount || 0 }} 次</span>
                </div>
                <div class="detail-item">
                  <span class="label">账户状态：</span>
                  <span class="value">
                    <el-tag :type="getStatusType(selectedUser.status)" size="small">
                      {{ getStatusText(selectedUser.status) }}
                    </el-tag>
                  </span>
                </div>
              </div>
            </el-col>
          </el-row>
          
          <div class="detail-section" v-if="selectedUser.remark">
            <h4>备注信息</h4>
            <p class="remark-text">{{ selectedUser.remark }}</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { User, UserForm } from '@/types'
import {
  Download,
  Plus,
  User as UserIcon,
  UserFilled,
  Avatar,
  Search,
  Refresh,
  View,
  Edit,
  MoreFilled,
  Key,
  Switch,
  Delete
} from '@element-plus/icons-vue'

const loading = ref(false)
const searchQuery = ref('')
const selectedUsers = ref<User[]>([])
const userFormRef = ref()

// 统计数据
const stats = ref({
  totalUsers: 156,
  activeUsers: 142,
  adminUsers: 8,
  newUsers: 12
})

// 筛选条件
const filters = ref<{
  role: string
  status: string
  department: string
  dateRange: string[] | null
}>({
  role: '',
  status: '',
  department: '',
  dateRange: null
})

// 分页
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 用户对话框
const userDialog = ref({
  visible: false,
  isEdit: false,
  loading: false
})

// 用户详情对话框
const userDetailDialog = ref({
  visible: false
})

// 选中的用户
const selectedUser = ref<User | null>(null)

// 用户表单
const userForm = ref<UserForm>({
  username: '',
  email: '',
  realName: '',
  phone: '',
  role: '',
  department: '',
  status: 'active',
  password: '',
  remark: ''
})

// 表单验证规则
const userFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email' as const, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 模拟用户数据
const users = ref([
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    realName: '系统管理员',
    phone: '13800138000',
    role: 'admin',
    department: 'tech',
    status: 'active',
    avatar: '',
    lastLoginAt: new Date('2024-01-17T10:30:00'),
    loginCount: 156,
    createdAt: new Date('2023-01-01'),
    remark: '系统超级管理员'
  },
  {
    id: 2,
    username: 'zhangsan',
    email: 'zhangsan@example.com',
    realName: '张三',
    phone: '13800138001',
    role: 'manager',
    department: 'tech',
    status: 'active',
    avatar: '',
    lastLoginAt: new Date('2024-01-17T09:15:00'),
    loginCount: 89,
    createdAt: new Date('2023-03-15'),
    remark: '技术部项目经理'
  },
  {
    id: 3,
    username: 'lisi',
    email: 'lisi@example.com',
    realName: '李四',
    phone: '13800138002',
    role: 'developer',
    department: 'tech',
    status: 'active',
    avatar: '',
    lastLoginAt: new Date('2024-01-16T18:45:00'),
    loginCount: 234,
    createdAt: new Date('2023-05-20'),
    remark: '前端开发工程师'
  },
  {
    id: 4,
    username: 'wangwu',
    email: 'wangwu@example.com',
    realName: '王五',
    phone: '13800138003',
    role: 'tester',
    department: 'tech',
    status: 'disabled',
    avatar: '',
    lastLoginAt: new Date('2024-01-10T14:20:00'),
    loginCount: 67,
    createdAt: new Date('2023-07-10'),
    remark: '测试工程师，暂时禁用'
  },
  {
    id: 5,
    username: 'zhaoliu',
    email: 'zhaoliu@example.com',
    realName: '赵六',
    phone: '13800138004',
    role: 'user',
    department: 'product',
    status: 'pending',
    avatar: '',
    lastLoginAt: null,
    loginCount: 0,
    createdAt: new Date('2024-01-15'),
    remark: '产品部新员工，待激活'
  }
])

// 过滤后的用户列表
const filteredUsers = computed(() => {
  let result = users.value
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(user => 
      user.username.toLowerCase().includes(query) ||
      user.email.toLowerCase().includes(query) ||
      (user.realName && user.realName.toLowerCase().includes(query))
    )
  }
  
  // 角色过滤
  if (filters.value.role) {
    result = result.filter(user => user.role === filters.value.role)
  }
  
  // 状态过滤
  if (filters.value.status) {
    result = result.filter(user => user.status === filters.value.status)
  }
  
  // 部门过滤
  if (filters.value.department) {
    result = result.filter(user => user.department === filters.value.department)
  }
  
  // 日期范围过滤
  if (filters.value.dateRange && filters.value.dateRange.length === 2) {
    const [startDate, endDate] = filters.value.dateRange
    result = result.filter(user => {
      const createdDate = dayjs(user.createdAt).format('YYYY-MM-DD')
      return createdDate >= startDate && createdDate <= endDate
    })
  }
  
  pagination.value.total = result.length
  
  // 分页
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return result.slice(start, end)
})

// 获取角色类型
const getRoleType = (role: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    'admin': 'danger',
    'manager': 'warning',
    'developer': 'primary',
    'tester': 'success',
    'user': 'info'
  }
  return types[role] || 'info'
}

// 获取角色文本
const getRoleText = (role: string) => {
  const texts: Record<string, string> = {
    'admin': '管理员',
    'manager': '项目经理',
    'developer': '开发者',
    'tester': '测试员',
    'user': '普通用户'
  }
  return texts[role] || role
}

// 获取状态类型
const getStatusType = (status: string): 'success' | 'warning' | 'danger' | 'info' | 'primary' => {
  const types: Record<string, 'success' | 'warning' | 'danger' | 'info' | 'primary'> = {
    'active': 'success',
    'disabled': 'danger',
    'pending': 'warning'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    'active': '活跃',
    'disabled': '禁用',
    'pending': '待激活'
  }
  return texts[status] || status
}

// 获取部门文本
const getDepartmentText = (department: string) => {
  const texts: Record<string, string> = {
    'tech': '技术部',
    'product': '产品部',
    'design': '设计部',
    'operation': '运营部',
    'hr': '人事部'
  }
  return texts[department] || department
}

// 格式化日期
const formatDate = (date: Date) => {
  return dayjs(date).format('MM-DD')
}

const formatTime = (date: Date) => {
  return dayjs(date).format('HH:mm')
}

const formatDateTime = (date: Date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 搜索处理
const handleSearch = () => {
  pagination.value.currentPage = 1
}

// 筛选处理
const handleFilter = () => {
  pagination.value.currentPage = 1
}

// 重置筛选
const resetFilters = () => {
  filters.value = {
    role: '',
    status: '',
    department: '',
    dateRange: null
  }
  searchQuery.value = ''
  pagination.value.currentPage = 1
}

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedUsers.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.value.currentPage = page
}

// 显示添加用户对话框
const showAddUserDialog = () => {
  userDialog.value.visible = true
  userDialog.value.isEdit = false
  resetUserForm()
}

// 查看用户
const viewUser = (user: any) => {
  selectedUser.value = user
  userDetailDialog.value.visible = true
}

// 编辑用户
const editUser = (user: any) => {
  userDialog.value.visible = true
  userDialog.value.isEdit = true
  userForm.value = { ...user }
}

// 用户操作处理
const handleUserAction = async (command: string, user: any) => {
  switch (command) {
    case 'resetPassword':
      await resetUserPassword(user)
      break
    case 'changeRole':
      changeUserRole()
      break
    case 'enable':
    case 'disable':
      await toggleUserStatus(user)
      break
    case 'delete':
      await deleteUser(user)
      break
  }
}

// 重置用户密码
const resetUserPassword = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要重置用户 ${user.username} 的密码吗？`,
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API重置密码
    ElMessage.success('密码重置成功，新密码已发送到用户邮箱')
  } catch {
    // 用户取消
  }
}

// 修改用户角色
const changeUserRole = () => {
  ElMessage.info('修改角色功能开发中...')
}

// 切换用户状态
const toggleUserStatus = async (user: any) => {
  const action = user.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}用户 ${user.username} 吗？`,
      `确认${action}`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API切换状态
    user.status = user.status === 'active' ? 'disabled' : 'active'
    ElMessage.success(`用户${action}成功`)
  } catch {
    // 用户取消
  }
}

// 删除用户
const deleteUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 ${user.username} 吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API删除用户
    const index = users.value.findIndex(u => u.id === user.id)
    if (index > -1) {
      users.value.splice(index, 1)
    }
    ElMessage.success('用户删除成功')
  } catch {
    // 用户取消
  }
}

// 批量修改角色
const batchChangeRole = () => {
  ElMessage.info('批量修改角色功能开发中...')
}

// 批量修改状态
const batchChangeStatus = () => {
  ElMessage.info('批量修改状态功能开发中...')
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？删除后无法恢复。`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API批量删除用户
    const selectedIds = selectedUsers.value.map((user: any) => user.id)
    users.value = users.value.filter(user => !selectedIds.includes(user.id))
    selectedUsers.value = []
    ElMessage.success('批量删除成功')
  } catch {
    // 用户取消
  }
}

// 导出用户
const exportUsers = () => {
  ElMessage.info('导出功能开发中...')
}

// 保存用户
const saveUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    userDialog.value.loading = true
    
    // 这里应该调用API保存用户
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (userDialog.value.isEdit) {
      // 更新用户
      const index = users.value.findIndex(u => u.id === userForm.value.id)
      if (index > -1) {
        users.value[index] = {
          ...users.value[index],
          ...userForm.value
        }
      }
      ElMessage.success('用户更新成功')
    } else {
      // 添加用户
      const newUser = {
        ...userForm.value,
        id: Date.now(),
        avatar: '',
        lastLoginAt: null,
        loginCount: 0,
        createdAt: new Date()
      }
      users.value.unshift(newUser)
      ElMessage.success('用户创建成功')
    }
    
    userDialog.value.visible = false
  } catch (error) {
    console.error('保存用户失败:', error)
  } finally {
    userDialog.value.loading = false
  }
}

// 重置用户表单
const resetUserForm = () => {
  userForm.value = {
    username: '',
    email: '',
    realName: '',
    phone: '',
    role: '',
    department: '',
    status: 'active',
    password: '',
    remark: ''
  }
  if (userFormRef.value) {
    userFormRef.value.clearValidate()
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 这里应该调用API加载用户数据
    await new Promise(resolve => setTimeout(resolve, 500))
    pagination.value.total = users.value.length
  } catch (error) {
    console.error('加载用户数据失败:', error)
    ElMessage.error('加载用户数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #fff;
}

.stat-icon.total {
  background: #409eff;
}

.stat-icon.active {
  background: #67c23a;
}

.stat-icon.admin {
  background: #e6a23c;
}

.stat-icon.new {
  background: #f56c6c;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.search-filters {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
}

.search-section {
  margin-bottom: 16px;
}

.search-section .el-input {
  max-width: 400px;
}

.filter-section {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-section .el-select {
  width: 120px;
}

.filter-section .el-date-picker {
  width: 240px;
}

.user-table {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  flex: 1;
}

.username {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.email {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.real-name {
  font-size: 12px;
  color: #999;
}

.last-login-time {
  font-size: 12px;
  color: #999;
}

.never-login {
  color: #999;
  font-style: italic;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f5f7fa;
  border-top: 1px solid #ebeef5;
}

.selected-info {
  color: #409eff;
  font-weight: 500;
}

.batch-buttons {
  display: flex;
  gap: 12px;
}

.pagination {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.user-detail {
  padding: 0;
}

.detail-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.user-basic-info h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #333;
}

.user-basic-info p {
  margin: 0 0 12px 0;
  color: #666;
}

.user-tags {
  display: flex;
  gap: 8px;
}

.detail-content {
  margin-top: 20px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
}

.detail-item .label {
  width: 80px;
  color: #666;
  font-size: 14px;
}

.detail-item .value {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.remark-text {
  color: #666;
  line-height: 1.6;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-section .el-select,
  .filter-section .el-date-picker {
    width: 100%;
  }
  
  .batch-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .detail-header {
    flex-direction: column;
    text-align: center;
  }
}
</style>